package com.tree.zk.selector;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;

import java.io.IOException;

/**
 * package com.tree.zk
 * description:
 *
 *
 * @author tree
 * @date 2019-08-22 20:24
 */
@Slf4j
public class LatchClient implements LeaderLatchListener {
    private final String name;

    private LeaderLatch leaderLatch;

    private CuratorFramework client;
    public LatchClient(CuratorFramework client, String path, String name) throws Exception {
        this.name = name;
        this.client = client;
        leaderLatch = new LeaderLatch(client, path);
        leaderLatch.addListener(this);
        leaderLatch.start();
    }

    @Override
    public void isLeader() {
        log.info(name + " is now the leader. ");
    }

    @Override
    public void notLeader() {
        log.info(name + " is not the leader. ");
    }

    public void stop() {
        try {
            leaderLatch.close();
        } catch (IOException e) {
        }
    }

    public boolean hasLeadership() {
        return leaderLatch.hasLeadership();
    }
    public CuratorFramework getClient() {
        return client;
    }

    public String getName() {
        return name;
    }




}
